/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.extjs.ajax;

import org.rails.extjs.javascript.Function;
import org.rails.extjs.javascript.JavaScript;
import org.rails.extjs.msg.SimpleWait;

public class SimpleRequest extends Request {

	protected IWait wait;

	public SimpleRequest(String method, String url) {
		super(method, url);
	}

	public SimpleRequest(String method, String url, IWait wait) {
		super(method, url);
		setWait(wait);
	}

	public SimpleRequest(String url) {
		super(METHOD_GET, url);
	}

	public SimpleRequest(String url, IWait wait) {
		super(METHOD_GET, url);
		setWait(wait);
	}

	public void setWait(IWait wait) {
		this.wait = wait;
	}

	public IWait getWait() {
		return wait;
	}

	public JavaScript hideWait() {
		return wait.hide();
	}
	
	public Function getFunction(){
		return new Function(getJavaScript());
	}
	
	public Function getFunction(String paramNames){
		return new Function(getJavaScript(),paramNames);
	}
	
	public JavaScript getJavaScript(){
		return new JavaScript(getScript());
	}


	@Override
	public String getScript() {
		
		script = new StringBuffer("");
		createItems();
		JavaScript hideWait = new JavaScript();
		if (wait != null) {
			script.append(wait.getWaitScript().getScript());
			script.append(wait.show().getScript());
			hideWait = hideWait();
			if(getFailure() == null){
				setFailure(new Function(wait.error(),"res,opt"));
			}
		}		
		JavaScript js = new JavaScript();	
		js.append("if(res.status==200){eval(res.responseText);}");	
		js.append(hideWait.getScript());
		setCallback(new Function(js, "opt,suc,res"));
		script.append("Ext.Ajax.request(");
		script.append(createOptions());
		script.append(");");

		return script.toString();
	}

}
